package cn.laixueit.service.impl;

import cn.laixueit.commons.Utils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Service
public class FileService {

    public String upLoadImg(MultipartFile file, HttpServletRequest request){
        if(file.getSize() == 0){
            return null;
        }
        String newFileName = null;
        try {
            String oldFileName = file.getOriginalFilename();
            String realPath = request.getSession().getServletContext().getRealPath("/img");
            String uuid = Utils.randUID();
            newFileName = uuid + "_" + oldFileName;
            File newFile = new File(realPath, newFileName);
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return "img/"+newFileName;
    }
}
